/*
 * @Author: January
 * @Date: 2021-05-02 15:11:40
 * @Description: built-in random number generator with provided entropy 
 *               and hash function.
 */

#include <libecc/rand/rand.h>
#include <libecc/hash/hash_algs.h>


static unsigned char entropy[ENTROPY_POOL_SIZE] = {0x98, 0x12, 0x6e, 0xb2, 0x16, 0xe6, 0x15, 0x5f, 0x4d,
                0x3e, 0x15, 0xba, 0x50, 0xc4, 0x11, 0x59, 0xc6, 0xb4, 0x40, 0xc5, 
                0x00, 0x9d, 0xca, 0xe7, 0xdd, 0xee, 0x93, 0xb4, 0xc7, 0x12, 0x86, 0x77};

void rand_bytes(unsigned char* buffer, int len) {
	hash_context ctx;
	const hash_mapping* sm3 = get_hash_by_type(SM3);
	int cur;

	while(len > 0) {
        sm3->hfunc_init(&ctx);
		sm3->hfunc_update(&ctx, entropy, sizeof(entropy));
		sm3->hfunc_finalize(&ctx, entropy);
		cur = (len > 32)? 32 : len;
        local_memcpy(buffer, entropy, len);
		len -= cur;
	}
}

void random_init(unsigned char* buf, int len) {
    int count = (len > ENTROPY_POOL_SIZE)? ENTROPY_POOL_SIZE : len;
    local_memcpy(entropy, buf, count);
}

int get_random(unsigned char *buf, unsigned short len) {
    rand_bytes(buf, len);
    return 0;
}
